package io.github.biezhi.wechat.api;

import io.github.biezhi.wechat.WeChatBot;
import lombok.Data;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Data
public class WeChatLoginMonitor {
    //超过指定登录时间（分）
    private static final int LOGIN_MINUTE = 10;
    //指定周期检查一下（秒）
    private static final int PERIOD_SECONDS = 30;

    private WeChatBot bot;
    private AtomicInteger count;

    public WeChatLoginMonitor(WeChatBot bot) {
        this.bot = bot;
        this.count = new AtomicInteger(0);
    }

    public void start() {

        final long periodCount = TimeUnit.MINUTES.toSeconds(LOGIN_MINUTE) / PERIOD_SECONDS;//检测次数

        final Timer timer = new Timer("wechat-login-monitor-" + bot.config().sysLoginAccount(), true);
        timer.schedule(new TimerTask() {
            private int checkCount = 0;

            @Override
            public void run() {
                if (bot.isRunning()) {
                    timer.cancel();//停止监控
                } else {
                    if (++checkCount > periodCount) {
                        timer.cancel();//停止监控
                        bot.stop();//停止bot
                    }
                }
            }
        }, TimeUnit.SECONDS.toMillis(PERIOD_SECONDS), TimeUnit.SECONDS.toMillis(PERIOD_SECONDS));
    }
}
